import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const loading = ref(false)
  const error = ref('')

  const isAuthenticated = computed(() => !!user.value)

  // 登录
  const login = async (username, password) => {
    loading.value = true
    error.value = ''

    try {
      const response = await authAPI.login({ username, password })

      if (response.success) {
        user.value = response.data.user
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return { success: true }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '登录失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (userData) => {
    loading.value = true
    error.value = ''

    try {
      const response = await authAPI.register(userData)

      if (response.success) {
        return { success: true, message: response.message }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '注册失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await authAPI.logout()
    } catch (err) {
      console.error('退出登录失败:', err)
    } finally {
      user.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      const response = await authAPI.getCurrentUser()
      if (response.success) {
        user.value = response.data.user
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return response.data.user
      }
    } catch (err) {
      console.error('获取用户信息失败:', err)
      // 如果获取用户信息失败，清除本地存储
      logout()
    }
  }

  // 更新用户信息
  const updateProfile = async (userData) => {
    loading.value = true
    error.value = ''

    try {
      const response = await authAPI.updateProfile(userData)

      if (response.success) {
        user.value = response.data.user
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return { success: true, message: response.message }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '更新失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    loading.value = true
    error.value = ''

    try {
      const response = await authAPI.changePassword(passwordData)

      if (response.success) {
        return { success: true, message: response.message }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err) {
      error.value = err.message || '修改密码失败'
      return { success: false, message: error.value }
    } finally {
      loading.value = false
    }
  }

  // 初始化认证状态
  const initAuth = async () => {
    const savedUser = localStorage.getItem('user')
    const token = localStorage.getItem('token')

    if (savedUser && token) {
      user.value = JSON.parse(savedUser)
      // 验证token是否有效
      try {
        await authAPI.verifyToken()
      } catch (err) {
        // token无效，清除本地存储
        logout()
      }
    }
  }

  // 验证token
  const verifyToken = async () => {
    try {
      const response = await authAPI.verifyToken()
      return response.success
    } catch (err) {
      return false
    }
  }

  return {
    user,
    loading,
    error,
    isAuthenticated,
    login,
    register,
    logout,
    getCurrentUser,
    updateProfile,
    changePassword,
    initAuth,
    verifyToken
  }
})
